﻿// Spun AJAX Framework
// Copyright (C) 2008 Blake Hegerle
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Net;

namespace Spun.Communications.Applications.Content
{
    using Hosting;

    public class ContentServer : IServer
    {
        #region IServer Members

        public void ProcessRequest(HttpListenerContext Context, string RelativePath)
        {
            var Match = PathRegex.Match(RelativePath);

            if (!Match.Success)
                throw new Exception("Not a valid filename: " + RelativePath);

            var Extension = Match.Groups[2].Value;

            Context.Response.ContentType = GetContentType(Extension);

            var ThisAssembly = Assembly.GetExecutingAssembly();
            using (var Stream = ThisAssembly.GetManifestResourceStream(this.GetType(), RelativePath))
            {
                var Buffer = new byte[10000];

                int Res;
                while ((Res = Stream.Read(Buffer, 0, Buffer.Length)) > 0)
                    Context.Response.OutputStream.Write(Buffer, 0, Res);
            }

            Context.Response.Close();
        }

        #endregion

        private string GetContentType(string Extension)
        {
            if (Extension.Equals("js", StringComparison.CurrentCultureIgnoreCase))
                return "text/javascript";
            else
                throw new Exception("Cannot determine content type for files with extension " + Extension);
        }

        private static Regex PathRegex;

        static ContentServer()
        {
            PathRegex = new Regex(@"^([-_.0-9a-zA-Z]+)\.([a-zA-Z]+)$");
        }
    }
}
